package org.ljy.testdemo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.Data;
import org.ljy.testdemo.config.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * 验证码代码案例
 */


@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    @Autowired
    private CaptchaProperties captchaProperties;


    private static final long VALID_MILLIS_TIME = 60 * 1000;//验证码有效时间60s

    /**
     *  获取验证码，展示到前端
     * @param session
     * @param response
     */
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response)  {
        //1.生成自定义验证码
        ICaptcha captcha = CaptchaUtil.createShearCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());

        try {
            //2.设置一些属性
            response.setContentType("image/jpeg"); //设置http返回值为图片类型(固定格式)
            response.setHeader("Pragma", "No-cache"); //禁止前端存在缓存(固定格式)
            //3.返回验证码图片
            captcha.write(response.getOutputStream());
            //4.将验证码保存起来--用于验证
            session.setAttribute(captchaProperties.getSession().getKey(),captcha.getCode()); //存储验证码
            session.setAttribute(captchaProperties.getSession().getDate(),new Date()); //存储当前时间
            //5.关闭流
            response.getOutputStream().close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  验证 验证码
     * @param session
     * @param captcha
     * @return
     */
    @RequestMapping("/check")
    public boolean  checkCaptcha(HttpSession session,String captcha) {
        System.out.println("后端接收验证码成功");
        if(!StringUtils.hasLength(captcha)) {
            return false;
        }
        //1.从session中获取到旧数据
        String captchaCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date oldDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        //2.对比验证
        if(captcha.equalsIgnoreCase(captchaCode)) { //比较验证码是否相同（忽略大小写）
            if(System.currentTimeMillis() - oldDate.getTime() < VALID_MILLIS_TIME) {//有效时间内
                return false;
            }
            return false;
        }
        return false;
    }



}
